<?php
namespace app\yhUtil\type;

use app\util\Entity;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Utils;

abstract class Base {
    use Entity;
    private $baseUrl = 'https://chat-go.jwzhd.com/open-apis/v1/';
    private $url = 'bot/send';
    private $token = '';
    protected $contentType;
    protected $recvType;
    protected $recvId;
    protected $parentId;

    public function __construct($message = [])
    {
        $msg = $message['event']['message'];
        $message['event']['sender']['senderType'] == 'user' ? $this->setUser($message['event']['sender']['senderId']) : $this->setGroup($message['event']['sender']['senderId']);
        $this->setParentMessage($msg['msgId']);
    }
    
    public function setToken($token = ''){
        $this->token = $token;
        return $this;
    }

    public function setParentMessage($parentId){
        $this->parentId = $parentId;
        return $this;
    }

    public function setUser($userId) {
        $this->recvType = 'user';
        $this->recvId = $userId;
        return $this;
    }

    public function setGroup($groupId) {
        $this->recvType = 'group';
        $this->recvId = $groupId;
        return $this;
    }
    protected function send() {
        $client = new Client();
        $res = $client->post(
            $this->baseUrl.$this->url.'?'.http_build_query(['token'=>$this->token]), 
            [
                'headers' => ['Content-Type' => 'application/json'],
                'body' => json_encode($this->__toArray())
            ]
        );
        return $res->getBody();
    }

    public function sendFile($file) {
        $type = $this->contentType;
        $client = new Client();
        $url = $type.'/upload?' . http_build_query(['token' => $this->token]);
        $res = $client->post($this->baseUrl . $url, [
            'multipart' => [
                [
                    'name' => $type,
                    'contents' => Utils::tryFopen($file, 'r'),
                    'filename' => basename($file), // 文件名
                ]
            ]
        ]);
        if(strpos($res->getHeader("content-type")[0], 'json')){
            return json_decode($res->getBody()->getContents(), true);
        }
        return $res->getBody();
    }
    public function run(){
        if(!$this->token) {
            $this->token = env('yh_token');
        }
        return $this->send();
    }
}